/**
 * 埋点数据 Redux Slice
 * @author lhx
 */

import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { TrackingState, TrackingEvent, TrackingConfig, ClickTrackingEvent } from '../../utils/types/trackingTypes';
import TrackingStorageLhx from '../../utils/storage/trackingStorageLhx';
import type { RootState } from '../index';

// 异步thunk：从本地存储加载数据
export const loadTrackingDataLhx = createAsyncThunk(
  'tracking/loadData',
  async () => {
    const storedData = await TrackingStorageLhx.getStoredData();
    return storedData;
  }
);

// 异步thunk：保存事件到本地存储
export const saveEventToStorageLhx = createAsyncThunk(
  'tracking/saveEvent',
  async (event: TrackingEvent) => {
    const success = await TrackingStorageLhx.addEvent(event);
    if (!success) {
      throw new Error('Failed to save event to storage');
    }
    return event;
  }
);

// 异步thunk：批量保存事件到本地存储
export const saveEventsToStorageLhx = createAsyncThunk(
  'tracking/saveEvents',
  async (events: TrackingEvent[]) => {
    const success = await TrackingStorageLhx.addEvents(events);
    if (!success) {
      throw new Error('Failed to save events to storage');
    }
    return events;
  }
);

// 初始状态
const initialState: TrackingState = {
  events: [],
  config: {
    enabled: true,
    batchSize: 20,
    uploadInterval: 30000,
    maxRetries: 3,
    endpoint: '/api/tracking',
    debugMode: __DEV__
  },
  currentSession: {
    sessionId: '',
    startTime: Date.now(),
    userId: undefined,
    pageStack: []
  },
  uploadQueue: [],
  isUploading: false,
  lastUploadTime: 0
};

const trackingSliceLhx = createSlice({
  name: 'trackingLhx',
  initialState,
  reducers: {
    // 添加事件到内存缓存
    addEvent: (state, action: PayloadAction<TrackingEvent>) => {
      state.events.push(action.payload);
      
      // 如果是点击事件且开启调试模式，打印日志
      if (state.config.debugMode && action.payload.eventType === 'click') {
        console.log('[TrackingLhx] Click event added:', action.payload);
      }
      
      // 限制内存中的事件数量
      if (state.events.length > 100) {
        state.events = state.events.slice(-80); // 保留最新的80个事件
      }
    },

    // 批量添加事件
    addEvents: (state, action: PayloadAction<TrackingEvent[]>) => {
      state.events.push(...action.payload);
      
      // 限制内存中的事件数量
      if (state.events.length > 100) {
        state.events = state.events.slice(-80);
      }
    },

    // 移除已上传的事件
    removeUploadedEvents: (state) => {
      state.events = state.events.filter(event => !event.uploaded);
    },

    // 更新配置
    updateConfig: (state, action: PayloadAction<Partial<TrackingConfig>>) => {
      state.config = { ...state.config, ...action.payload };
    },

    // 初始化会话
    initSession: (state, action: PayloadAction<{
      sessionId: string;
      userId?: string;
    }>) => {
      state.currentSession = {
        sessionId: action.payload.sessionId,
        startTime: Date.now(),
        userId: action.payload.userId,
        pageStack: []
      };
    },

    // 添加页面到堆栈
    pushPage: (state, action: PayloadAction<string>) => {
      state.currentSession.pageStack.push(action.payload);
      
      // 限制页面堆栈长度
      if (state.currentSession.pageStack.length > 20) {
        state.currentSession.pageStack = state.currentSession.pageStack.slice(-15);
      }
    },

    // 弹出页面
    popPage: (state) => {
      state.currentSession.pageStack.pop();
    },

    // 设置上传状态
    setUploadingStatus: (state, action: PayloadAction<boolean>) => {
      state.isUploading = action.payload;
    },

    // 添加到上传队列
    addToUploadQueue: (state, action: PayloadAction<TrackingEvent[]>) => {
      state.uploadQueue = [...state.uploadQueue, ...action.payload];
    },

    // 清空上传队列
    clearUploadQueue: (state) => {
      state.uploadQueue = [];
    },

    // 标记事件为已上传
    markEventsAsUploaded: (state, action: PayloadAction<string[]>) => {
      const eventIds = action.payload;
      state.events = state.events.map(event => {
        if (eventIds.includes(event.id)) {
          return { ...event, uploaded: true };
        }
        return event;
      });
      
      // 从上传队列中移除已上传的事件
      state.uploadQueue = state.uploadQueue.filter(
        event => !eventIds.includes(event.id)
      );
    },

    // 更新最后上传时间
    updateLastUploadTime: (state) => {
      state.lastUploadTime = Date.now();
    },

    // 增加事件重试次数
    incrementRetryCount: (state, action: PayloadAction<string[]>) => {
      const eventIds = action.payload;
      state.events = state.events.map(event => {
        if (eventIds.includes(event.id)) {
          return { ...event, retryCount: event.retryCount + 1 };
        }
        return event;
      });
    },

    // 清除所有数据（用于重置或调试）
    clearAllData: (state) => {
      state.events = [];
      state.uploadQueue = [];
      state.isUploading = false;
      state.lastUploadTime = 0;
    }
  },

  extraReducers: (builder) => {
    // 加载本地存储数据
    builder.addCase(loadTrackingDataLhx.fulfilled, (state, action) => {
      const storedData = action.payload;
      if (storedData) {
        // 只加载未上传的事件到内存
        state.events = storedData.events.filter(event => !event.uploaded).slice(-50);
        state.config = { ...state.config, ...storedData.config };
        state.currentSession = {
          ...storedData.session,
          pageStack: state.currentSession.pageStack // 保持当前页面堆栈
        };
      }
    });

    builder.addCase(loadTrackingDataLhx.rejected, (state, action) => {
      console.error('[TrackingLhx] Failed to load data from storage:', action.error);
    });

    // 保存事件到本地存储
    builder.addCase(saveEventToStorageLhx.fulfilled, (state, action) => {
      if (state.config.debugMode) {
        console.log('[TrackingLhx] Event saved to storage:', action.payload.id);
      }
    });

    builder.addCase(saveEventToStorageLhx.rejected, (state, action) => {
      console.error('[TrackingLhx] Failed to save event to storage:', action.error);
    });

    // 批量保存事件到本地存储
    builder.addCase(saveEventsToStorageLhx.fulfilled, (state, action) => {
      if (state.config.debugMode) {
        console.log('[TrackingLhx] Events saved to storage:', action.payload.length);
      }
    });

    builder.addCase(saveEventsToStorageLhx.rejected, (state, action) => {
      console.error('[TrackingLhx] Failed to save events to storage:', action.error);
    });
  }
});

// 导出actions
export const {
  addEvent,
  addEvents,
  removeUploadedEvents,
  updateConfig,
  initSession,
  pushPage,
  popPage,
  setUploadingStatus,
  addToUploadQueue,
  clearUploadQueue,
  markEventsAsUploaded,
  updateLastUploadTime,
  incrementRetryCount,
  clearAllData
} = trackingSliceLhx.actions;

// 选择器
export const selectTrackingState = (state: RootState) => state.trackingLhx;
export const selectTrackingEvents = (state: RootState) => state.trackingLhx.events;
export const selectTrackingConfig = (state: RootState) => state.trackingLhx.config;
export const selectCurrentSession = (state: RootState) => state.trackingLhx.currentSession;
export const selectUnuploadedEvents = (state: RootState) => 
  state.trackingLhx.events.filter(event => !event.uploaded);
export const selectIsUploading = (state: RootState) => state.trackingLhx.isUploading;

// 导出reducer
export default trackingSliceLhx.reducer;